import { useEffect } from "react"
import { useDispatch, useSelector } from "react-redux"
import { useLocation, useNavigate } from "react-router"
import { setUser } from "../store/action"
import { fetchUserFromStorage } from "./storage"


let control = false;

export function setControl(co) {
    control = co;
}

export function initDrag(id) {
    let box = document.getElementById(id)
    var mouseDown = false
    var mouseX,mouseY
    box.style.transform = "translate(-50px,150px)"
    box.onmousedown = function(ev) {
        if(!control)return ;
        mouseDown = true
        mouseX = ev.clientX
        mouseY = ev.clientY
    }
    document.onmouseup = function(ev) {
        if(!control)return ;
        mouseDown = false
    }
    
    document.onmousemove = function(ev) {
        if(!control)return ;
        if(!mouseDown)return ; 
        // 获取之前的位置
        let s = box.style.transform
        let t1 = s.indexOf('(',0)
        let t2 = s.indexOf('px',0)
        let posX = parseInt(s.slice(t1+1,t2))
        t1 = s.indexOf(',',0)
        t2 = s.indexOf("px",t2+2)
        let posY = parseInt(s.slice(t1+1,t2))

        box.style.transform = `translate(${ev.clientX-mouseX+posX}px,${ev.clientY-mouseY+posY}px)`
        mouseX = ev.clientX
        mouseY = ev.clientY
    }
    return () => {
        box.onmousedown = null;
        document.onmousemove = null;
        document.onmouseup = null;
    }
}

// 权限
export function useCheckAndNavigate() {
    let user = fetchUserFromStorage();
    const navigate = useNavigate();
    const location = useLocation();
    const nuser = useSelector(state=>state.user);
    const dispatcher = useDispatch();
    useEffect(()=>{
        if(!user) {
            navigate("/login");
        } else  {
            if(!nuser.name) {
                dispatcher(setUser(user));
            }
            if(location.pathname === "/login") {
                navigate("/home");
            }
        }
    },[]);
}